'use strict'

import axios from 'axios'
import qs from 'qs'
import Vue from 'vue'
import router from '@/router/index'
import store from '@/store/index'
import { Local } from '@/util/storage/storage.js'
import { Session } from '@/util/storage/session.js'
// import { refreshToken } from './user.js'
import { refresh } from '../permission.js'

const host = window.location.host
// 设置默认请求地址
// axios.defaults.baseURL = host === 'codelover.club' ? '/pro' : '/test';
// axios.defaults.baseURL = process.env.NODE_ENV == 'development' ? '/' : '/'; // 开发环境设置了反向代理

// 默认请求时间限制
axios.defaults.timeout = 10000;

// 设置CORS跨域允许携带资源凭证
axios.defaults.withCredentials = true;

// 设置POST请求头：告知服务器请求主题的数据格式
// axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8';
// axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';  // url传参 a=xxx&b=xxx
// axios.defaults.transformRequest = data => qs.stringify(data)

/**
 * 设置请求拦截器
 * TOKEN校验(JWT)：接收服务器返回的token，存储到vuex/本地存储中，每次向服务器发送请求把token带上
 */
axios.interceptors.request.use(async (config) => {
  if (config.headers['content-Type'] && config.headers['content-Type'] === 'application/x-www-form-urlencoded') {
      config.data = qs.stringify(config.data)
  }
  // token直接从localstorage里面获取 防止跨页token没刷新时store的token不一致 携带token
  let userInfo = await Session.get('userInfo', true)
  let token = null
  if (userInfo) {
    token = userInfo.accessToken
  } else {
    const user = store.state.user
    if (user.userInfo.refreshToken) {
      config.headers.Authorization = 'Bearer ' + user.userInfo.accessToken
      let result = await refresh(user, user.userInfo.refreshToken)
      // 等待当前用户信息的token信息更新成果后，将最新的token赋值
      console.log(result);
      if (result?.data?.accessToken) token = result.data.accessToken
    }
  }
  token && (config.headers.Authorization = 'Bearer ' + token);
  // 上传文件的token  
  let apiUrlArr = ['/v_api/upload', '/api/utils/uploadfiles', '/api/utils/unzipfile', '/api/teacher/multistudydata', '/api/queryresult/getcurrfinalreport', '/api/teacher/listbycurrNo', '/api/choose/calscores', '/api/queryresult/listbycurrNo', '/api/choose/mytaskresults']
  if (apiUrlArr.indexOf(config.url) !== -1 || config.url.indexOf('/api/queryresult/listbycurrNo') !== -1) {
    config.headers.token = 'EKSXVqWOvMQ3C3T1'
    // 上传文件请求时间限制
    config.timeout = 120000
  }
  return config
}, error => {
  return Promise.reject()
})
/**
 * 设置响应拦截
 */
axios.interceptors.response.use(response => {
  // if (response.status === 200) {
  // 信息验证异常 跳转登录页面
  if (response.data.errno === 10021 && response.data.message == '您的账号可能已过期，或者在别处登录。请新开标签页重新登录！') {
    store.dispatch('user/Logout')
    router.push({
      name: 'Home'
    })
    return
  }
  if ((response.data.errno === 10005 && response.data.message !== '您尚未登录')) {
    Vue.prototype.$antdMessage.error({
      content: response.data.message,
    })
    store.dispatch('user/Logout')
    router.push({
      name: 'Login'
    })
  }
  return Promise.resolve(response.data);
}, async ({ error, response }) => {
  if (response && response.status === 401 && response.data?.error === 'jwt expired') { // invalid signature
    const user = store.state.user
    // let userInfo = user.userInfo
    const rToken = user.userInfo.refreshToken;
    if (rToken) {
      await refresh(user, rToken, response)
    } else Vue.prototype.$antdMessage.error({
      content: '请重新登录'
    })
  }
  else if (response && response.status === 401) {
    store.dispatch("user/Logout")
    Vue.prototype.$antdMessage.warning({
      content: '用户信息已过期,请重新登录!'
    })
  }
  else if (response && response.status === 500) {
    return Vue.prototype.$antdMessage.error({
      content: '服务器异常'
    })
  }
  else Vue.prototype.$antdMessage.error({
    content: error?.message || error || '网络异常'
  })
  return Promise.reject(error)
})

// 封装axios原型到vue的$http属性内
Vue.prototype.$http = axios

export default axios;